/**
 * <b>项目名称：</b>网络应用框架<br/>
 * <b>包    名：</b>com.hhwy.framework.datasource.service<br/>
 * <b>文 件 名：</b>IDatasourceService.java<br/>
 * <b>版本信息：</b><br/>
 * <b>日    期：</b>2014年8月4日-下午2:57:08<br/>
 * <b>Copyright (c)</b> 2014恒华伟业科技股份有限公司-版权所有<br/>
 * 
 */
package com.hhwy.framework.datasource.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import com.hhwy.framework.common.Constants;
import com.hhwy.framework.datasource.DatasourceHelper;
import com.hhwy.framework.datasource.domain.DatasourceConfig;

 /**
 * <b>类 名 称：</b>IDatasourceService 动态数据源配置<br/>
 * <b>类 描 述：</b><br/>
 * <b>创 建 人：</b>lihuiming<br/>
 * <b>修 改 人：</b>Administrator<br/>
 * <b>修改时间：</b>2014年8月4日 下午2:57:08<br/>
 * <b>修改备注：</b><br/>
 * @version 1.0.0<br/>
 */
public class DatasourceService {

	/**
	 * getDatasourceConfig(获取数据源配置)<br/>
	 * @param dsMap
	 * @return 
	 * DatasourceConfig
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws NoSuchMethodException 
	 * @exception 
	 * @since  1.0.0
	 */
	private DatasourceConfig getDatasourceConfig(Map<String, Object> dsMap) throws Exception{
		DatasourceConfig dc = new DatasourceConfig();
		
		Set<String> properySet = BeanUtils.describe(dc).keySet();
		Iterator<String> it = dsMap.keySet().iterator();
		
		while(it.hasNext()){
			String columnName = it.next();
			String key = getPropertyName(columnName);
			if(properySet.contains(key) && dsMap.get(columnName) != null)
				BeanUtils.setProperty(dc, key, dsMap.get(columnName));
			
		}
		
		return dc;
	}
	private String getPropertyName(String pName) {
		pName = pName.toLowerCase();
		String[] name = pName.split("_");
		pName = name[0];
		for (int i = 1; i < name.length; i++) {
			pName = pName + name[i].substring(0,1).toUpperCase() + name[i].substring(1);
		}
		return pName;
	}
	/**
	 * getAllConfig(获取所有数据源配置)<br/>
	 * @return 
	 * List<DatasourceConfig>
	 * @exception 
	 * @since  1.0.0
	 */
	public List<DatasourceConfig> getAllConfig(){
		List<DatasourceConfig> dcList = new ArrayList<>();
		String sql = "select * from "+Constants.DATASOURCE_CONFIG_TABLE;
		try {
			List<Map<String,Object>> dsList = getJdbcTemplate().queryForList(sql);
			for (Map<String,Object> dsMap : dsList) {
				
				try {
					DatasourceConfig dsConfig = getDatasourceConfig(dsMap);
					dcList.add(dsConfig);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		} catch (Exception e) {
			new RuntimeException("未找到动态数据源配置表：T_DATASOURCE_CONFIG",e).printStackTrace();
		}
		
		return dcList;
	}
	
	public JdbcTemplate getJdbcTemplate(){
		JdbcTemplate jdbcTemplate = new JdbcTemplate();
		jdbcTemplate.setDataSource(DatasourceHelper.getDefaultDataSource());
		return jdbcTemplate;
		
	}
	
	public boolean existsTDatasourceConfigTable() {
		String sql="SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '"+Constants.DATASOURCE_CONFIG_TABLE+"' and table_schema=(select database())";
		
		int count = getJdbcTemplate().queryForObject(sql,Integer.class);
		return count != 0;
	}
	
	public void createTDatasourceConfigTable() {
		
		StringBuilder sb=new StringBuilder();
		
		sb.append(" CREATE TABLE `t_datasource_config` ( ");
		sb.append(" `id` varchar(32) NOT NULL, ");
		sb.append(" `create_time` datetime DEFAULT NULL, ");
		sb.append(" `create_user` varchar(32) DEFAULT NULL, ");
		sb.append(" `update_time` datetime DEFAULT NULL, ");
		sb.append(" `update_user` varchar(32) DEFAULT NULL, ");
		sb.append(" `app_name` varchar(255) DEFAULT NULL, ");
		sb.append(" `driver` varchar(255) DEFAULT NULL, ");
		sb.append(" `filters` varchar(255) DEFAULT NULL, ");
		sb.append(" `initial_size` int(11) DEFAULT NULL, ");
		sb.append(" `max_active` int(11) DEFAULT NULL, ");
		sb.append(" `min_millis` int(11) DEFAULT NULL, ");
		sb.append(" `min_idle` int(11) DEFAULT NULL, ");
		sb.append(" `password` varchar(255) DEFAULT NULL, ");
		sb.append(" `remove_abandoned` bit(1) DEFAULT NULL, ");
		sb.append(" `remove_timeout` int(11) DEFAULT NULL, ");
		sb.append(" `test_on_borrow` bit(1) DEFAULT NULL, ");
		sb.append(" `test_on_return` bit(1) DEFAULT NULL, ");
		sb.append(" `test_while_idle` bit(1) DEFAULT NULL, ");
		sb.append(" `time_millis` int(11) DEFAULT NULL, ");
		sb.append(" `url` varchar(255) DEFAULT NULL, ");
		sb.append(" `user_name` varchar(255) DEFAULT NULL, ");
		sb.append(" `validation_query` varchar(255) DEFAULT NULL, ");
		sb.append(" PRIMARY KEY (`id`) ");
		sb.append(" ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
		
		getJdbcTemplate().execute(sb.toString());
	}
	
}
